<template>
  <div class="dept-role-page">

    <div class="back">
      <span @click="backPageHandle" class="button"><i class="el-icon-back"></i>返回</span>
      <span class="split">|</span>
      <span :style="{ '--color': this.themeColor }" class="name">{{ deptName }}</span>
      <span>部门关联角色</span>
    </div>

    <transition name="el-zoom-in-top">
      <el-form v-show="searchRoleVisible" inline size="mini" :model="searchRoleForm" ref="searchRoleForm"
               @keyup.enter.native="searchRoleHandle">
        <el-form-item label="角色检索">
          <el-input v-model="searchRoleForm.word" clearable placeholder="请选择检索的用户名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchRoleForm.status" clearable placeholder="请选择状态" class="role-status-input">
            <el-option label="可用" value="0"></el-option>
            <el-option label="不可用" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="loading" @click="searchRoleHandle" type="primary" icon="el-icon-search">查询</el-button>
        </el-form-item>
      </el-form>
    </transition>

    <div class="d-r-tool">
      <el-button :disabled="loading" @click="$refs.deptRoleSaveUpdateDialog.openDialog({ deptId }, false)"
                 type="primary" size="mini" plain icon="el-icon-plus">添加</el-button>

      <el-button :disabled="dataLoad || roleSelection.length === 0" @click="deleteDeptRoleHandle(undefined)"
                 type="danger" size="mini" plain icon="el-icon-delete">删除</el-button>

      <!-- 还差一个刷新表格事件 -->
      <right-tool-bar :search-visible="searchRoleVisible" :search-load="loading"
                      @toggle-search="searchRoleVisible = !searchRoleVisible" @refresh-table="getDeptRoleList" />
    </div>

    <el-table
      v-loading="dataLoad"
      element-loading-text="关联角色数据加载中"
      element-loading-spinner="el-icon-loading"
      :data="roleList"
      @selection-change="val => this.roleSelection = val"
      ref="deptRoleTable"
    >
      <el-table-column type="selection" align="center" width="50"></el-table-column>
      <el-table-column prop="roleName" align="center" label="角色名称"></el-table-column>
      <el-table-column prop="roleKey" align="center" label="角色键"></el-table-column>
      <el-table-column prop="useRange" align="center" label="生效范围">
        <template v-slot="{ row }">
          {{ row.useRange | valueFormat(useRangeList) }}
        </template>
      </el-table-column>
      <el-table-column prop="useLeader" align="center" label="领导专属">
        <template v-slot="{ row }">
          {{ row.useLeader | valueFormat(useLeaderList) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" align="center" label="状态">
        <template v-slot="{ row }">
          {{ row.status | valueFormat(statusList) }}
        </template>
      </el-table-column>
      <el-table-column prop="remark" align="center" label="备注"></el-table-column>
      <el-table-column prop="createTime" align="center" label="创建时间">
      </el-table-column>
      <el-table-column prop="createUser" align="center" label="创建用户"></el-table-column>
      <el-table-column align="center" label="操作" width="150">
        <template v-slot="scope">
          <el-button type="text" icon="el-icon-edit"
                     @click="$refs.deptRoleSaveUpdateDialog.openDialog(scope.row, true)">
            修改
          </el-button>

          <el-dropdown :disabled="loading">
            <span class="el-dropdown-link fz12" v-bind:style="{ color: themeColor, marginLeft: '7px' }">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-user"
                                @click.native="$refs.roleUserRelationDialog.init(scope.row, false)">
                查看用户
              </el-dropdown-item>
              <el-dropdown-item v-show="scope.row.status === 1" divided icon="el-icon-check"
                                @click.native="updateDeptRoleStatusHandle(scope.row, 0)">
                使用
              </el-dropdown-item>
              <el-dropdown-item v-show="scope.row.status === 0" divided icon="el-icon-close"
                                @click.native="updateDeptRoleStatusHandle(scope.row, 1)">
                禁用
              </el-dropdown-item>
              <el-dropdown-item icon="el-icon-delete" @click.native="deleteDeptRoleHandle(scope.row)">
                删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表格分页插件 -->
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :disabled="dataLoad"
      :current-page="searchRoleForm.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="searchRoleForm.limit"
      :total="totalNum"
      layout="total, sizes, prev, pager, next, jumper"
      class="paging">
    </el-pagination>

    <!-- 角色关联用户弹出框 -->
    <role-user-relation ref="roleUserRelationDialog" />

    <!-- 部门关联角色弹出框 -->
    <DeptRoleSaveUpdate ref="deptRoleSaveUpdateDialog" @refresh="getDeptRoleList" />
  </div>
</template>

<script>
  import RightToolBar from '@/components/common/right-toolbar';
  import RoleUserRelation from "@/components/role/role-user/relation.vue";
  import DeptRoleSaveUpdate from '@/components/dept/dept-role/save-update';

  export default {
    layout: 'admin',
    name: "admin-system-dept-role",
    components: { RightToolBar, RoleUserRelation, DeptRoleSaveUpdate },
    data() {
      return {
        // 部门id
        deptId: undefined,
        // 部门名称
        deptName: undefined,
        // 部门已关联角色列表
        roleList: [],
        // 部门已关联角色数量
        totalNum: 0,
        // 角色表格被选中数据的行
        roleSelection: [],
        // 角色检索表单对象
        searchRoleForm: {
          // 角色名称
          word: '',
          // 角色状态
          status: '',
          // 页码
          page: 1,
          // 每页大小
          limit: 10
        },

        // 使用范围枚举列表
        useRangeList: [
          {
            name: '本部门',
            value: 0
          },
          {
            name: '所有子部门',
            value: 1
          }
        ],
        // 是否领导专属枚举列表
        useLeaderList: [
          {
            name: '是',
            value: 0
          },
          {
            name: '否',
            value: 1
          }
        ],
        // 状态枚举列表
        statusList: [
          {
            name: '可用',
            value: 0
          },
          {
            name: '禁用',
            value: 1
          }
        ],

        // 数据是否加载[false-不加载 true-加载]
        dataLoad: false,
        // 按钮是否可被点击[false-可以被点击 true-不可被点击]
        buttonLoad: false,
        // 角色检索表单是否显示
        searchRoleVisible: true,


      }
    },
    computed: {
      // 主题颜色
      themeColor() {
        return this.$store.state.settings.theme
      },
      // 数据加载中
      loading() {
        return this.dataLoad || this.buttonLoad
      }
    },
    filters: {
      valueFormat(value, list) {
        for (let item of list) {
          if (item.value === value) {
            return item.name;
          }
        }
        return '';
      }
    },
    created() {
      if (process.client) {
        let query = this.$route.query
        if (!query.dept || !query.deptName) {
          this.$router.push('/admin/system/dept')
        }
        this.deptId = query.dept
        this.deptName = query.deptName

        this.getDeptRoleList()
      }
    },
    methods: {
      /**
       * 回到部门管理页面事件
       */
      backPageHandle() {
        this.$router.push({ name: 'admin-system-dept' })
      },
      /**
       * 角色列表检索事件
       */
      searchRoleHandle() {
        this.pageIndex = 1

        this.getDeptRoleList()
      },
      /**
       * 获取角色数据列表方法
       */
      getDeptRoleList() {
        let searchRoleForm = this.searchRoleForm
        let body = {
          deptId: this.deptId,
          ...searchRoleForm
        }
        // 开始表格数据加载
        this.dataLoad = true;
        this.$axios.$post('/sys/dept-role/page/list', body)
          .then(({ data:page }) => {
            this.roleList = page.list
            this.totalNum = page.totalNum
          })
          .catch(() => {})
          .finally(() => {
            // 表格数据加载结束
            this.dataLoad = false;
          })
      },
      /**
       * 表格每页显示数量变化事件
       * @param val 最新值
       */
      sizeChangeHandle (val) {
        this.searchRoleForm.page = 1
        this.searchRoleForm.limit = val
        this.getDeptRoleList()
      },
      /**
       * 表格页码切换事件
       * @param val 最新值
       */
      currentChangeHandle (val) {
        if (this.searchRoleForm.page === val) {
          return
        }
        this.searchRoleForm.page = val
        this.getDeptRoleList()
      },
      /**
       * 更新角色状态事件
       * @param {Object} role   角色对象
       * @param {Number} status 最新状态
       */
      updateDeptRoleStatusHandle(role, status) {
        // 按钮不可被点击
        this.buttonLoad = true;
        this.$axios.$post('/sys/dept-role/update/status', { idList: [ role.roleId ], status: status })
          .then(() => {
            // 变更角色状态
            role.status = status;
          })
          .catch(() => {})
          .finally(() => {
            // 按钮恢复可点击
            this.buttonLoad = false;
          });
      },
      /**
       * 删除角色事件
       * @param deptRole 角色数据对象
       */
      deleteDeptRoleHandle(deptRole) {
        let roleIds = [];
        let roleNames = [];
        if (!!deptRole) {
          roleIds.push(deptRole.id);
          roleNames.push(deptRole.roleName);
        } else {
          let roleSelection = this.roleSelection;
          roleIds = roleSelection.map(role => {
            roleNames.push(role.roleName);
            return role.id;
          });
        }
        this.$confirm(`您确定要删除【${this.deptName}】部门关联的【${roleNames}】角色吗，是否继续？`,
          '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        }).then(() => {
          // 按钮不可被点击
          this.buttonLoad = true;

          return this.$axios.$delete('/sys/dept-role/delete', { data: roleIds });
        })
        .then(() => {
          this.notify('success', '操作成功', `成功删除【${roleNames}】角色数据`);

          this.getDeptRoleList();
        })
        .catch(() => {})
        .finally(() => {
          // 按钮恢复可点击
          this.buttonLoad = false;
        });
      },
    }
  }
</script>

<style scoped>
  .dept-role-page .back {
    font-size: 14px;
    margin-bottom: 20px;
  }
  .dept-role-page .back .button {
    cursor: pointer;
  }
  .dept-role-page .back .split {
    margin: 0 5px;
  }
  .dept-role-page .back .name {
    --color: black;
    color: var(--color);
  }
  .dept-role-page .d-r-tool {
    margin-bottom: 7px;
  }
  .dept-role-page .paging {
    text-align: right;
    margin: 7px;
  }
</style>
